package com.liuqi.loggers.api;

import com.liuqi.loggers.core.Configuration;
import com.liuqi.loggers.core.Constants;
import com.liuqi.loggers.core.Context;
import com.liuqi.loggers.core.LoggingContext;
import com.liuqi.loggers.core.appender.ConsoleAppender;
import com.liuqi.loggers.core.config.GenericConfigurator;
import java.io.InputStream;

/**
 * 初始化日志上下文
 *
 * @author liuqi
 * @date 2024/10/14 15:21
 **/
public class ContextBinder {

    private static final String CONFIG_XML_FILENAME = "loggers.xml";

    private static Context context;

    public static Context getContext() {
        if (context != null) {
            return context;
        } else {
            synchronized (ContextBinder.class) {
                if (context == null) {
                    try {
                        initDefaultContext();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return context;
    }

    public static void setContext(Context context) {
        if (context != null) {
            context.getLogger(Context.ROOT_LOGGER_NAME).warn("set logger context " + context );
        }
        ContextBinder.context = context;
    }

    /**
     * 优先读取resource目录下的{@link #CONFIG_XML_FILENAME}配置文件
     *
     * @throws Exception
     */
    private static void initDefaultContext() throws Exception {
        LoggingContext context;
        InputStream inputStream = ContextBinder.class.getClassLoader().getResourceAsStream(CONFIG_XML_FILENAME);
        if (inputStream != null) {
            // 创建 Context 实例
            context = new LoggingContext(Context.ROOT_LOGGER_NAME);
            // 加载xml, 并初始化 Context
            GenericConfigurator configurator = new GenericConfigurator();
            configurator.setContext(context);
            configurator.doConfigure(inputStream);
        } else {
            // 控制台输出
            ConsoleAppender appender = new ConsoleAppender();
            // appender name
            appender.setName("console");
            // 设置编码器
            appender.setEncoder(Constants.defaultEncoder());
            // 日志配置项
            Configuration config = new Configuration();
            // 添加 Appender
            config.addAppender(appender);
            // 创建 Context 实例
            context = new LoggingContext(Context.ROOT_LOGGER_NAME, config);
            // start
            context.start();
        }
        // set
        ContextBinder.context = context;
    }

}
